<!--
  * 云喇叭管理
-->
<template>
  <!---------- 查询表单form begin ----------->

  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="台卡设备码" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.code" placeholder="输入台卡设备码" />
      </a-form-item>
      <a-form-item label="商户名称" class="smart-query-form-item">
        <CustomSelect
          style="width: 200px"
          v-model:value="queryForm.merchantId"
          :placeholder="'请选择'"
          :api="merchantApi.page"
          :queryParams="merchantParams"
          queryParamKey="companyNameLeftLike"
          labelField="companyName,no"
        />
      </a-form-item>
      <a-form-item label="批次号" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.batchId" placeholder="输入批次号" />
      </a-form-item>
      <a-form-item label="状态" class="smart-query-form-item">
        <a-select v-model:value="queryForm.activeStatus" style="width: 180px" allowClear :options="ACTIVE_STATUS" placeholder="请选择状态" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-title">数据列表</div>
      <div class="smart-table-operate-block">
        <a-button @click="showBindMch(state.selectedRowKeys, 'ids')" type="primary" size="small" :disabled="!hasSelected"> 批量划拨/召回 </a-button>
        <a-button @click="showBindMch(state.selectedRowKeys, 'batchId')" type="primary" size="small"> 批次划拨/召回 </a-button>
        <a-button @click="showForm" type="primary" size="small">
          <template #icon>
            <PlusOutlined />
          </template>
          新增
        </a-button>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table
      size="small"
      :row-selection="{ selectedRowKeys: state.selectedRowKeys.map((e) => e.id), onSelect: onSelectFn }"
      :dataSource="tableData"
      :columns="columns"
      rowKey="id"
      bordered
      :loading="tableLoading"
      :pagination="false"
    />
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>

  <CodeForm v-model:open="codeOptions.open" :formType="codeOptions.type" :rowData="codeOptions.data" @ok="onSearch" />
  <SelectMch v-model:open="bindMchOptions.open" @ok="bindMchOk">
    <template #content>
      <a-form v-if="bindMchOptions.bindType == 'batchId'">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="批次号" required>
              <a-input v-model:value="bindBatchId" placeholder="请输入批次号" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <a-radio-group
        v-if="bindMchOptions.bindType == 'ids' || bindMchOptions.bindType == 'batchId'"
        v-model:value="state.operation"
        :options="[
          { label: '绑定商户', value: 1 },
          { label: '解绑商户', value: 0 },
        ]"
      />
    </template>
  </SelectMch>
  <!-- 预览二维码 -->
  <a-modal v-model:open="openImg" title="二维码预览" :footer="false">
    <div style="text-align: center" class="m-t-10">
      <canvas id="qrCanvas" width="300" height="330"></canvas>
    </div>
  </a-modal>
</template>
<script setup>
  import { reactive, ref, onMounted, computed, getCurrentInstance, h, nextTick } from 'vue'
  import { merchantApi } from '/@/api/business/b-operation/merchant/merchant-api.js'
  import { codeApi } from '/@/api/business/b-operation/code/code-api'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { Button, Switch, Modal, message } from 'ant-design-vue'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { selectDictLabel, privilege } from '/@/utils/common'
  import { ACTIVE_STATUS, START_STOP } from '/@/constants/dict'
  import CodeForm from './code-form.vue'
  import SelectMch from '/@/components/business/comment/SelectMch.vue'
  import { isEmpty } from 'lodash'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  const { proxy } = getCurrentInstance()
  // ---------------------------- 表格列 ----------------------------
  const cloudDevice = computed(() => {
    // 0云喇叭 1云打印
    return route.path.includes('cloud-speaker') ? 0 : 1
  })

  const columns = ref([
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      customRender: ({ index }) => {
        return (queryForm.pageNo - 1) * queryForm.pageSize + index + 1
      },
    },
    {
      title: '台卡设备号',
      dataIndex: 'code',
      ellipsis: true,
    },
    {
      title: '批次号',
      dataIndex: 'batchId',
      ellipsis: true,
    },
    {
      title: '商户名称',
      dataIndex: 'merchantName',
      ellipsis: true,
    },
    {
      title: '门店名称',
      dataIndex: 'storeName',
      ellipsis: true,
    },
    {
      title: '台卡状态',
      dataIndex: 'activeStatus',
      customRender: (column) => selectDictLabel(ACTIVE_STATUS, column.text),
      ellipsis: true,
    },
    {
      title: '是否启用',
      dataIndex: 'status',
      customRender: (column) => (column.text == 1 ? '是' : '否'),
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'cTime',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      minWidth: 180,
      customRender: ({ record }) => {
        return h('div', [
          isEmpty(record.merchantName)
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    showBindMch(record)
                  },
                },
                '绑定',
              )
            : h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    showUnBindMch(record)
                  },
                },
                '解绑',
              ),
          // privilege('manufacturer:find_id')
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              onClick: () => {
                showForm(record, 'view')
              },
            },
            '详情',
          ),
          isEmpty(record.merchantName)
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    delRow(record)
                  },
                },
                '删除',
              )
            : '',
          !isEmpty(record.merchantName)
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    viewMpImg(record)
                  },
                },
                '查看台卡',
              )
            : '',
          !isEmpty(record.merchantName)
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    downloadChange(record)
                  },
                },
                '下载台卡',
              )
            : '',
        ])
      },
    },
  ])

  const state = reactive({
    selectedRowKeys: [],
    loading: false,
    operation: 1,
  })
  const hasSelected = computed(() => state.selectedRowKeys.length > 0)
  const onSelectFn = (record) => {
    // 根据id判断当前点击的是否被选中
    const isS = state.selectedRowKeys.findIndex((obj) => obj.id == record.id)
    if (isS >= 0) {
      state.selectedRowKeys.splice(isS, 1)
    } else {
      state.selectedRowKeys.push(record)
    }
  }

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    codeType: 1,
    code: undefined,
    activeStatus: undefined,
    merchantId: undefined,
    batchId: undefined,
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  /* 切换厂商 */
  function handleChange(data) {
    queryForm.deviceModelId = undefined
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    let queryParams = { ...queryForm, deviceType: cloudDevice.value }
    try {
      let queryResult = await codeApi.page(queryParams)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  // const getBusinessName = (value) => {
  //   const item = CHANNEL_BUSINESS_TYPE.find((item) => item.value === value)
  //   return item ? item.itemName : null
  // }

  onMounted(() => {
    queryData()
    // getBusinessList()
  })

  // ---------------------------- 添加/修改 ----------------------------
  const codeOptions = ref({
    open: false,
    data: null,
    type: 'add',
  })

  function showForm(data, type) {
    codeOptions.value.open = true
    codeOptions.value.data = data
    codeOptions.value.type = type
  }
  // 绑定的批次号
  const bindBatchId = ref('')
  // 绑定商户
  const bindMchOptions = ref({
    open: false,
    data: null,
    bindType: 'id',
  })
  const showBindMch = (data, type = 'id') => {
    bindMchOptions.value.open = true
    bindMchOptions.value.bindType = type
    bindBatchId.value = ''
    state.operation = 1
    if (Array.isArray(data)) {
      bindMchOptions.value.data = data
    } else {
      bindMchOptions.value.data = [data]
    }
  }
  const bindMchOk = (val) => {
    if (bindMchOptions.value.bindType == 'ids' && state.operation == 0) {
      // 批量解绑
      showUnBindMch(state.selectedRowKeys)
      return
    }
    if (bindMchOptions.value.bindType == 'batchId' && state.operation == 0) {
      // 批次解绑
      if (isEmpty(bindBatchId.value)) return message.error('请输入批次号')
      showUnBindMch()
      return
    }
    if (bindMchOptions.value.bindType == 'batchId' && state.operation == 1) {
      // 批次绑定
      if (isEmpty(bindBatchId.value)) return message.error('请输入批次号')
      if (isEmpty(val)) return message.error('绑定商户请选择商户')
      const data = { merchantId: val[0].id, merchantName: val[0].companyAbbrName, no: val[0].no, batchId: bindBatchId.value }
      codeApi.bindMerchant(data).then((res) => {
        bindMchOptions.value.open = false
        onSearch()
      })
      return
    }
    // 批量绑定
    if (isEmpty(val)) return message.error('绑定商户请选择商户')
    const data = { merchantId: val[0].id, merchantName: val[0].companyAbbrName, no: val[0].no, ids: bindMchOptions.value.data.map((e) => e.id) }
    codeApi.bindMerchant(data).then((res) => {
      bindMchOptions.value.open = false
      state.selectedRowKeys = []
      onSearch()
    })
  }

  // 解绑商户
  const showUnBindMch = (record) => {
    if (!Array.isArray(record) && !isEmpty(record)) {
      record = [record]
    }
    Modal.confirm({
      title: '提示',
      content: '确定要解绑商户吗?',
      okText: '解绑',
      okType: 'danger',
      async onOk() {
        const data = isEmpty(record)
          ? { merchantId: null, merchantName: null, no: null, batchId: bindBatchId.value }
          : { merchantId: null, merchantName: null, no: null, ids: record.map((item) => item?.id) }

        codeApi.bindMerchant(data).then((res) => {
          bindMchOptions.value.open = false
          state.selectedRowKeys = []
          onSearch()
        })
      },
      cancelText: '取消',
      onCancel() {},
    })
  }
  // ---------------------------- 批量删除 ----------------------------

  // 删除
  async function delRow(record) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除该数据吗?',
      okText: '删除',
      okType: 'danger',
      async onOk() {
        rowDelete(record)
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  //请求删除
  async function rowDelete(record) {
    try {
      SmartLoading.show()
      await codeApi.delete({ id: record.id })
      message.success('删除成功')
      queryData()
    } catch (e) {
      console.log(e)
      smartSentry.captureError(e)
    } finally {
      SmartLoading.hide()
    }
  }

  // ---------------------------- 二维码码牌激活下载 ----------------------------
  const downloadChange = async (record) => {
    // console.log('record==>', record)
    const params = {
      merchantId: record.merchantId,
      storeId: record.id,
    }
    await codeApi.downloadActive(params).then((res) => {
      const url = res.data.urlBase64Image
      //下载
      const link = document.createElement('a')
      link.href = url
      link.download = res.data.code + '.png'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
  }
  // ---------------------------- 二维码码牌预览 ----------------------------
  const openImg = ref(false)
  const imgUrl = ref('')
  const storeName = ref('')
  const viewMpImg = async (record) => {
    // console.log('record==>', record)
    storeName.value = record.code
    const params = {
      merchantId: record.merchantId,
      storeId: record.id,
    }
    await codeApi.downloadActive(params).then((res) => {
      imgUrl.value = res.data.urlBase64Image
      openImg.value = true
      console.log('imgUrl1==>', imgUrl.value)
      // 使用 nextTick 确保 DOM 更新完成后再调用 makeCanvas
      nextTick(() => {
        makeCanvas()
      })
    })
  }
  const makeCanvas = () => {
    // 直接执行 canvas 操作，不等待 DOMContentLoaded 事件
    const canvas = document.getElementById('qrCanvas')
    const ctx = canvas.getContext('2d')

    // 绘制红色背景
    ctx.fillStyle = '#B81614'
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    // 二维码相关配置和绘制
    const qrSize = 200 // Size of the QR code within the canvas
    const qrMargin = 50
    const qrImage = new Image()
    qrImage.src = imgUrl.value //qrCode.createDataURL(4) // Scale factor for QR code image

    qrImage.onload = function () {
      // 绘制白色方块和二维码
      ctx.fillStyle = 'white'
      ctx.fillRect(qrMargin, qrMargin, qrSize, qrSize) // White square to contain QR code
      ctx.drawImage(qrImage, qrMargin, qrMargin, qrSize, qrSize)

      // 绘制四个角的装饰线条
      drawCornerLs(ctx, 40, 40, qrSize + 20, qrSize + 20, 20)

      // 添加门店文本信息
      ctx.fillStyle = '#fff'
      ctx.font = 'bold 16px Arial'
      ctx.textAlign = 'center'
      // ctx.fillText(`门店:${storeName.value}`, canvas.width / 2, canvas.height - 30)

      ctx.fillText(`NO:${storeName.value}`, canvas.width / 2, canvas.height - 30)
    }

    /**
     * 绘制四个角的L形（开口朝中间）
     * @param {CanvasRenderingContext2D} ctx - Canvas绘图上下文
     * @param {number} x - 容器左上角x坐标
     * @param {number} y - 容器左上角y坐标
     * @param {number} width - 容器宽度
     * @param {number} height - 容器高度
     * @param {number} length - L形每条边的长度（向中间延伸的距离）
     * @param {string} [color='#fff'] - 线段颜色（默认白色）
     * @param {number} [lineWidth=3] - 线段宽度（默认3像素）
     */
    function drawCornerLs(ctx, x, y, width, height, length, color = '#fff', lineWidth = 3) {
      // 配置绘图样式（线帽设为'square'让L形角更整齐）
      ctx.strokeStyle = color
      ctx.lineWidth = lineWidth
      ctx.lineCap = 'square'

      // ---- 1. 左上角L形（上边+左边，开口向右下）----
      ctx.beginPath()
      ctx.moveTo(x, y) // 起点：左上角顶点
      ctx.lineTo(x + length, y) // 上边：向右延伸length
      ctx.moveTo(x, y) // 回到起点
      ctx.lineTo(x, y + length) // 左边：向下延伸length
      ctx.stroke()

      // ---- 2. 右上角L形（上边+右边，开口向左下）----
      ctx.beginPath()
      ctx.moveTo(x + width, y) // 起点：右上角顶点
      ctx.lineTo(x + width - length, y) // 上边：向左延伸length
      ctx.moveTo(x + width, y) // 回到起点
      ctx.lineTo(x + width, y + length) // 右边：向下延伸length
      ctx.stroke()

      // ---- 3. 右下角L形（右边+下边，开口向左上）----
      ctx.beginPath()
      ctx.moveTo(x + width, y + height) // 起点：右下角顶点
      ctx.lineTo(x + width, y + height - length) // 右边：向上延伸length
      ctx.moveTo(x + width, y + height) // 回到起点
      ctx.lineTo(x + width - length, y + height) // 下边：向左延伸length
      ctx.stroke()

      // ---- 4. 左下角L形（下边+左边，开口向右上）----
      ctx.beginPath()
      ctx.moveTo(x, y + height) // 起点：左下角顶点
      ctx.lineTo(x + length, y + height) // 下边：向右延伸length
      ctx.moveTo(x, y + height) // 回到起点
      ctx.lineTo(x, y + height - length) // 左边：向上延伸length
      ctx.stroke()
    }
  }
</script>

<style lang="less" scoped>
  .notice-alert {
    margin-bottom: 16px;

    :deep(.ant-alert) {
      &.ant-alert-warning {
        background-color: #f59a23;
        border: none;
        padding: 16px 24px;

        .ant-alert-message {
          color: #ffffff;
        }
      }
    }
  }

  .smart-table-btn-block {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    justify-content: space-between;
  }

  .smart-table-title {
    font-size: 16px;
    font-weight: 500;
  }

  .smart-table-operate-block {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .custom-modal {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }

  .modal-content {
    width: 400px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    text-align: center;
  }

  #modal-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .modal-message {
    display: flex;
    align-items: center; /* 垂直居中 */
    margin-bottom: 20px;
  }

  #modal-icon {
    color: #f0ad4e; /* 警告图标的颜色 */
    font-size: 24px;
    margin-right: 10px;
  }

  #modal-content {
    font-size: 14px;
    color: #333;
  }

  .modal-buttons {
    display: flex;
    justify-content: center;
    gap: 10px;
  }

  #modal-ok {
    background-color: #007bff;
    color: #fff;
    border: none;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
  }

  #modal-cancel {
    background-color: #f0f0f0;
    color: #333;
    border: 1px solid #ccc;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
  }
</style>
